package cn.mntool.es;

import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * describe: 人员管理控制器
 *
 * @author lianying
 * @date 2020/07/26
 */
@RestController
public class PeopleController {
    @Autowired
    private PreBuiltTransportClient preBuiltTransportClient;

    @GetMapping("/people/{type}/{id}")
    public ResponseEntity get(@PathVariable String type,@PathVariable String id){
        if(id==null)
        {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        GetResponse documentFields = preBuiltTransportClient.prepareGet("people", type, id).get();
        if(!documentFields.isExists())
        {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity(documentFields.getSource(), HttpStatus.OK);
    }

    /**
     * 新增人员
     *
     * @param name
     * @param country
     * @param age
     * @param date
     * @return
     */
    @PostMapping("/people/man")
    public ResponseEntity put(
            @RequestParam("name")String name
            ,@RequestParam("country")String country
            ,@RequestParam("age")Integer age
            ,@RequestParam("date")String date
    ){
        try {
            XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject()
                    .field("name", name)
                    .field("country", country)
                    .field("age", age)
                    .field("date", date)
                    .endObject();
            IndexResponse indexResponse = preBuiltTransportClient.prepareIndex("people", "man").setSource(xContentBuilder).get();
            return new ResponseEntity(indexResponse.getId(),HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 查询人员
     *
     * @param name
     * @param country
     * @param ageGt
     * @param ageLt
     * @param date
     * @return
     */
    @PostMapping("/query/people/man")
    public ResponseEntity search(
            @RequestParam(value = "name",required = false)String name
            ,@RequestParam(value = "country",required = false)String country
            ,@RequestParam(value = "ageGt" ,defaultValue = "0")int ageGt
            ,@RequestParam(value = "ageLt",required = false)Integer ageLt
            ,@RequestParam(value = "date",required = false)String date
    ){
        BoolQueryBuilder boolQuery= QueryBuilders.boolQuery();
        if(name!=null)
        {
            boolQuery.must(QueryBuilders.matchQuery("name",name));
        }
        if(country!=null)
        {
            boolQuery.must(QueryBuilders.matchQuery("country",country));
        }
        if(date!=null)
        {
            boolQuery.must(QueryBuilders.matchQuery("date",date));
        }
        RangeQueryBuilder rangeQueryBuilder=QueryBuilders.rangeQuery("age").from(ageGt);
        if(ageLt!=null&&ageLt>0)
        {
            rangeQueryBuilder.to(ageLt);
        }
        boolQuery.filter(rangeQueryBuilder);
        SearchRequestBuilder searchRequestBuilder = preBuiltTransportClient.prepareSearch("people")
                .setTypes("man")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(boolQuery)
                .setFrom(0)
                .setSize(10);
        SearchResponse searchResponse = searchRequestBuilder.get();
        List<Map<String,Object>> data=new ArrayList<>();
        for (SearchHit searchHit:searchResponse.getHits()) {
            data.add(searchHit.getSource());
        }
        return new ResponseEntity(data,HttpStatus.OK);
    }
}
